<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>HTML5模拟微信聊天界面</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no"/>

    <link rel="stylesheet" href="./css/index.css">
    <style>
        .sysMessage{
            text-align: center;
            color: #9a9a9a;
        }
    </style>
</head>
<body>
<div id="container">
    <div class="header">
        <span style="float: left;" id="name">大兔聊天室</span>
        <span style="float: right;" id="time">14:21</span>
    </div>
    <ul class="content">
        <!-- 欢迎加入qq群：454796847、135430763 -->
    </ul>
    <div class="footer">
        <div id="user_face_icon">
            <img src="./avatar/1 (1).jpg" alt="">
        </div>
        <textarea id="text" name="" id="" placeholder="说点什么吧..."></textarea>
        <!--<input id="text" type="text" placeholder="说点什么吧...">-->
        <span id="btn">发送</span>
    </div>
</div>
</body>

<script src="./js/jquery.min.js"></script>
<script src="./js/layer/layer.js"></script>
<script>
    var arrIcon = ['./avatar/1 (1).jpg','./avatar/1 (2).jpg'];
    var num = 0;     //控制头像改变
    var iNow = -1;    //用来累加改变左右浮动
    var icon = document.getElementById('user_face_icon').getElementsByTagName('img');
    var btn = document.getElementById('btn');
    var text = document.getElementById('text');
    var content = document.getElementsByTagName('ul')[0];
    var img = content.getElementsByTagName('img');
    var span = content.getElementsByTagName('div');



    var ws;// webSocket连接

    /*时钟*/
    setInterval(function(){
        var myDate = new Date();
        var time = add0(myDate.getHours()) + ':'+ add0(myDate.getMinutes()) + ':' + add0(myDate.getSeconds());
        $('#time').html(time)
    },1000);

    //前置补0
    function add0(number){
        return number>9?number:'0'+number;
    }

    //阻止默认右键事件
    document.oncontextmenu=function(ev){
        var oEvent= ev||event;
        console.log(oEvent)
        //oEvent.preventDefault();
    };

    //右键点击 复制内容
    function copy(text){
        var oEvent= event;

        if(event.button!=2){
            return ;
        }

        //全选文本
        if (document.body.createTextRange) {
            var range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if (window.getSelection) {
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
        } else {
            alert("none");
            return false;
        }
        // 复制选中的内容
        /*        if(document.execCommand('copy', false, null)){
                    layer.msg('复制成功',{icon:1});
                } else{
                    layer.msg('复制失败，没有内容被选中',{icon:2});
                }*/
    }

    function init(){
        if (!("WebSocket" in window))
        {
            sendMessage(3,"您的浏览器不支持webSocket！")
            return false;
        }
        ws = new WebSocket("ws://127.0.0.1:7777/ws");

        //接收消息
        ws.onmessage = function(evt){
            if(evt.data == 'heartbeat'){
                console.log("心跳：",evt.data)
            }else{
                sendMessage(1,evt.data);
                console.log("接收消息：",evt.data)
            }
        }

        //连接断开
        ws.onclose = function () {
            sendMessage(3,"与服务器失去连接");
            console.log("连接断开")
        }
        sendMessage(3,"连接服务器成功！")
    }

    window.onload = function(){

        init();//初始化

        // 右边  左边头像
        icon[0].onclick = function(){
            if(num==0){
                this.src = arrIcon[1];
                num = 1;
            }else if(num==1){
                this.src = arrIcon[0];
                num = 0;
            }
        };

        //点击发送消息
        btn.onclick = function(){
            sendMessage(0,text.value);
            ws.send(text.value)
            // var res = sendMessage(num,text.value);
            // if(res && num==0){
            //     text.value = '';
            // }
        }
    };

    /**
     * 发送消息
     * @param num   对象 0 自己 1 对方  2 系统消息
     * @param text  发送的内容
     */
    function  sendMessage(num,text){
        if(text ==''){
            alert('不能发送空消息');
        }else {

            iNow++;
            if(num==0){
                //自己

                html = '<li><img class="imgright" src="'+arrIcon[num]+'"><div class="spanright" onmouseup="copy(this)">'+text+'</div></li>';

                // img[iNow].className += 'imgright';
                // span[iNow].className += 'spanright';
                // getMessage(text);
            }else if(num==1){
                //对方

                html = '<li><img class="imgleft" src="'+arrIcon[num]+'"><div class="spanleft" onmouseup="copy(this)">'+text+'</div></li>';


                // img[iNow].className += 'imgleft';
                // span[iNow].className += 'spanleft';
            }else{
                //系统消息
                html = '<li><p class="sysMessage">'+text+'</p></li>';
            }
            content.innerHTML += html;
            // 内容过多时,将滚动条放置到最底端
            content.scrollTop=content.scrollHeight;
        }
    }

    function getMessage(text){
        var name = $('#name').html();
        var url = '{:url("api/robot","get")}?debug=1';
        $('#name').html('对方正在输入...');
        $.post(url,{text:text},function(res){
            $('#name').html(name);
            if(res.code==200){
                sendMessage(1,res.msg);
            }else{
                layer.msg(res.msg,{icon:5});
            }
        })
    }

</script>
</html>